<?php


declare (strict_types=1);

namespace app\admin\controller\store;

use app\admin\controller\Controller;
use app\admin\model\store\User as UserModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 机构后台菜单控制器
 * Class Menu
 * @package app\store\controller
 */
class User extends Controller
{
    public function all()
    {
        $model = new UserModel;
        $list = $model->getAllList();
        return $this->renderSuccess(compact('list'));
    }

    public function tree()
    {
        $model = new UserModel;
        $list = $model->getTreeList();
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 菜单列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        $model = new UserModel;
        $list = $model->getList();
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 添加菜单
     * @return array
     */
    public function add()
    {
        // 新增记录
        $model = new UserModel;
        if ($model->add($this->postForm())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 更新菜单
     * @param $menuId
     * @return array|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function edit(int $menuId)
    {
        // 菜单详情
        $model = UserModel::detail($menuId);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 设置菜单绑定的Api
     * @param int $menuId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setApis(int $menuId)
    {
        // 菜单详情
        $model = UserModel::detail($menuId);
        // 更新记录
        if ($model->setApis($this->postForm())) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 删除菜单
     * @param $menuId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delete(int $menuId)
    {
        // 菜单详情
        $model = UserModel::detail($menuId);
        if (!$model->remove()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

}
